package me.seu.demo.controller;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.service.netty.connection.Connection;
import me.seu.demo.service.netty.connection.ConnectionManager;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Enumeration;

/**
 * 长连接管理的接口
 *
 * @author liangfeihu
 * @number 53669
 * @since 2021/4/8 下午6:21
 */
@Slf4j
@RestController
@RequestMapping("/connection")
public class ConnectionController {

    @GetMapping("/check")
    public ResponseEntity checkTcpSize() {
        int size = ConnectionManager.getInstance().tcpSize();
        log.info("[ConnectionController] tcp size={}", size);
        Enumeration<String> keys = ConnectionManager.getInstance().keys();
        return ResponseEntity.ok(keys);
    }

    @GetMapping("/notify")
    public ResponseEntity sendMsg(@RequestParam("deviceId") String deviceId) throws Exception {
        Connection conn = ConnectionManager.getInstance().getConn(deviceId);
        if (conn == null) {
            return ResponseEntity.badRequest().body("无此链接或该设备已下线");
        }
        ChannelHandlerContext ctx = conn.getCtx();
        if (ctx.channel().isWritable()) {
            // 发送下行指令
            byte[] notifyPacket = new byte[]{0x78, 0x78, 0x0E, (byte) 0x80, 0x08, 0x00, 0x00, 0x00, 0x00, 0x73,
                    0x6F, 0x73, 0x23, 0x00, 0x01, 0x6D, 0x6A, 0x0D, 0x0A};
            ctx.pipeline().writeAndFlush(Unpooled.wrappedBuffer(notifyPacket));
        } else {
            ctx.pipeline().close();
        }

        return ResponseEntity.ok("[ConnectionController] send down msg success");
    }

}
